package com.easybuilder.common.utils;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {

    //获取文件资源输入流
    public static InputStream getResourceStream(String filePath) {
        InputStream ins = null;
        String path = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        try {
            URL resource = FileUtil.class.getClassLoader().getResource(filePath);
            if (resource != null) {
                ins = resource.openStream();
            } else {
                path = path.substring(1, path.indexOf("/target/classes/")) + "/src/main/resources/" + filePath;
                ins = new FileInputStream(path);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ins;
    }

    // 获取实力类保存路径
    public static String getEntityPath(String classPath) {
        String path = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        return path.replaceFirst("//", "").replaceAll("target/classes/","src/main/java/") + classPath;
    }

    /** 生成java entity */
    public static void createJavaEntity(String classPath, String table_name, List<Map<String, String>> fields, List<String> packages) {
        String entityPath = getEntityPath(classPath.replaceAll("\\.", "/"));
        String className = StringUtil.column2Field(table_name);
        // 首字母大写
        String first = String.valueOf(className.charAt(0));
        className = className.replaceFirst(first, first.toUpperCase());
        // java文件名
        String fileName = className + ".java";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(entityPath + "/" + fileName));){
            // 当前包名
            bw.write("package " + classPath + ";");
            bw.newLine();
            bw.newLine();
            // 导入包名
            for (String p : packages) {
                // java.lang包不需要引入
                if (p.contains("java.lang")) {
                    continue;
                }
                // 日期类型采用java.util.Date
                if ("java.sql.Timestamp".equals(p)) {
                    p = "java.util.Date";
                }
                bw.write("import " + p + ";");
                bw.newLine();
            }
            bw.newLine();
            bw.newLine();
            // 类名
            bw.write("@Entity");
            bw.newLine();
            bw.write("@Table(name = \"" + table_name + "\")");
            bw.newLine();
            bw.write("@Data");
            bw.newLine();
            bw.write("public class " + className + " {");
            String space = "    ";
            for (Map<String, String> field : fields) {
                bw.newLine();
                String fieldName = field.get("fieldName");
                String fieldType = field.get("fieldType");
                String key = field.get("key");
                String comment = field.get("comment");
                // 如果是主键，添加主键注解
                if ("PRI".equals(key)) {
                    bw.write("    @Id");
                    bw.newLine();
                    bw.write("    @GeneratedValue(generator = \"JDBC\") //设置主键自动增长，执行insert操作后，主键会回写到实体类");
                    bw.newLine();
                }
                // 如果是java.sql.Timestamp
                if (fieldType.contains("Timestamp")) {
                    fieldType = fieldType.replaceAll("Timestamp", "Date");
                }
                // 写入java字段名
                bw.write(space + "/** " + comment + " */");
                bw.newLine();
                // 写入java字段名
                bw.write(space + "private " + fieldType  + " " + fieldName + ";" );
                bw.newLine();
            }
            bw.newLine();
            bw.newLine();
            bw.write("}");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /** 生成java dao */
    public static void createJavaDao(String classPath, String tableName) {
        String entityPath = getEntityPath(classPath.replaceAll("\\.", "/"));
        String className = StringUtil.column2Field(tableName);
        // 首字母大写
        String first = String.valueOf(className.charAt(0));
        className = className.replaceFirst(first, first.toUpperCase());
        // java文件名
        String fileName = className + "Dao.java";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(entityPath + "/" + fileName));) {
            // 当前包名
            bw.write("package " + classPath + ";");
            bw.newLine();
            bw.newLine();
            // 引入报名
            List<String> packages = Arrays.asList("com.easybuilder.common.base.dao.BaseDao",
                    classPath.replace("dao","entity") + "." + className,
                    "tk.mybatis.mapper.common.ExampleMapper",
                    "org.springframework.stereotype.Repository");
            for (String p : packages) {
                bw.write("import " + p + ";");
                bw.newLine();
            }
            // 写类名
            bw.newLine();
            bw.newLine();
            bw.write("@Repository");
            bw.newLine();
            bw.write("public interface "+className+"Dao extends BaseDao<"+className+">, ExampleMapper<"+className+"> {\n" +
                    "\n" +
                    "}");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 生成java servcie */
    public static void createJavaService(String classPath, String tableName) {

        // 1.生成接口

        // 2.生成实体类
    }


    /** 文件压缩 */
    public static void createZipFile(File file) throws IOException {
        if (file == null || !file.exists()) {
            return;
        }

        if (file.isFile()) {
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File("压缩文件.zip")));
            zos.putNextEntry(new ZipEntry(file.getName()));
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String line = "";
            while ((line = br.readLine()) != null) {
                zos.write(line.getBytes(StandardCharsets.UTF_8));
            }
            br.close();
            zos.close();
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File("E://压缩文件.zip")));
            for (File f : files) {
                zos.putNextEntry(new ZipEntry(f.getName()));
                FileInputStream fis = new FileInputStream(f);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                String line = "";
                while ((line = br.readLine()) != null) {
                    zos.write(line.getBytes(StandardCharsets.UTF_8));
                }
                br.close();
            }
            zos.close();
        }
    }

    public static void main(String[] args) throws IOException {
        createZipFile(new File("E://文件压缩"));
    }
}
